using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Text.Json;
using SvgToFontConverter.Models;

namespace SvgToFontConverter.Services
{
    /// <summary>
    /// Fontello CLI服务类，负责SVG到字体的转换
    /// </summary>
    public class FontelloCliService
    {
        private readonly SvgProcessorService _svgProcessor;
        
        public FontelloCliService()
        {
            _svgProcessor = new SvgProcessorService();
        }
        /// <summary>
        /// 验证Fontello CLI配置是否有效
        /// </summary>
        /// <param name="config">Fontello CLI配置</param>
        /// <returns>是否有效</returns>
        public bool ValidateFontelloCliConfig(FontelloCliConfig config)
        {
            if (string.IsNullOrWhiteSpace(config.NodeJsPath))
                return false;
                
            var nodePath = Path.Combine(config.NodeJsPath, "node.exe");
            if (!File.Exists(nodePath))
                return false;
            
            if (string.IsNullOrWhiteSpace(config.FontelloCliPath))
                return false;
                
            var packageJsonPath = Path.Combine(config.FontelloCliPath, "package.json");
            if (!File.Exists(packageJsonPath))
                return false;
                
            try
            {
                var packageJson = File.ReadAllText(packageJsonPath);
                return packageJson.Contains("fontello-cli");
            }
            catch
            {
                return false;
            }
        }
        
        /// <summary>
        /// 将SVG路径坐标缩放到字体坐标系统
        /// </summary>
        /// <param name="svgContent">SVG内容</param>
        /// <param name="pathData">原始路径数据</param>
        /// <param name="actualWidth">输出参数：实际字符宽度</param>
        /// <returns>缩放后的路径数据</returns>
        private string ScalePathToFontCoordinates(string svgContent, string pathData, out double actualWidth)
        {
            try
            {
                // 解析viewBox
                var viewBoxMatch = System.Text.RegularExpressions.Regex.Match(svgContent, @"viewBox\s*=\s*[""']([^""']*)[""']", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                double sourceX = 0, sourceY = 0, sourceWidth = 100, sourceHeight = 100;
                
                if (viewBoxMatch.Success)
                {
                    var viewBoxValues = viewBoxMatch.Groups[1].Value.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (viewBoxValues.Length >= 4)
                    {
                        double.TryParse(viewBoxValues[0], out sourceX);
                        double.TryParse(viewBoxValues[1], out sourceY);
                        double.TryParse(viewBoxValues[2], out sourceWidth);
                        double.TryParse(viewBoxValues[3], out sourceHeight);
                        Debug.WriteLine($"解析viewBox: x={sourceX}, y={sourceY}, width={sourceWidth}, height={sourceHeight}");
                    }
                }
                else
                {
                    // 如果没有viewBox，尝试解析width和height属性
                    var widthMatch = System.Text.RegularExpressions.Regex.Match(svgContent, @"width\s*=\s*[""']([^""']*)[""']", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    var heightMatch = System.Text.RegularExpressions.Regex.Match(svgContent, @"height\s*=\s*[""']([^""']*)[""']", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    
                    if (widthMatch.Success && heightMatch.Success)
                    {
                        var widthStr = widthMatch.Groups[1].Value.Replace("px", "").Replace("pt", "");
                        var heightStr = heightMatch.Groups[1].Value.Replace("px", "").Replace("pt", "");
                        double.TryParse(widthStr, out sourceWidth);
                        double.TryParse(heightStr, out sourceHeight);
                        Debug.WriteLine($"解析width/height: width={sourceWidth}, height={sourceHeight}");
                    }
                }
                
                // 字体标准尺寸定义（与SvgProcessorService保持一致）
                double fontEmSize = 1000; // 标准字体EM尺寸
                double baselineRatio = 0.8;  // 基线位置（从顶部算起80%）
                double baseline = fontEmSize * baselineRatio;  // 基线Y坐标
                
                // 固定字符高度为750单位（从基线到大写字母稍上一点）
                double targetCharHeight = 750.0;  // 固定高度750单位
                
                // 根据固定高度计算缩放比例，保持纵横比
                double scale = targetCharHeight / sourceHeight;
                
                // 移除宽度限制，让字符宽度根据高度缩放自然确定
                
                // 确保最小缩放比例，字符不能太小
                double minScale = Math.Min(targetCharHeight / sourceHeight, (fontEmSize * 0.5) / Math.Max(sourceWidth, sourceHeight));
                if (scale < minScale)
                {
                    scale = minScale;
                }
                
                // 限制最大缩放比例
                if (scale > 20.0)
                {
                    scale = 20.0;
                }
                
                // 计算字符实际宽度（缩放后的宽度）
                double actualCharWidth = sourceWidth * scale;
                
                // 计算偏移：字符左侧对齐到左线位置
                double targetOffsetX = 0;  // X轴：左侧对齐到左线
                double targetOffsetY = baseline - sourceHeight * scale;  // Y轴：基线减去缩放后的字符高度
                
                Debug.WriteLine($"计算缩放参数: scale={scale}, targetOffsetX={targetOffsetX}, targetOffsetY={targetOffsetY}");
                
                // 缩放路径坐标
                var scaledPath = ScalePathCoordinates(pathData, sourceX, sourceY, sourceHeight, scale, targetOffsetX, targetOffsetY);
                
                // 输出实际字符宽度
                actualWidth = actualCharWidth;
                
                return scaledPath;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"缩放路径坐标失败: {ex.Message}");
                actualWidth = 1000; // 默认宽度
                return pathData; // 返回原始路径
            }
        }
        
        /// <summary>
        /// 缩放路径中的所有坐标
        /// </summary>
        /// <param name="pathData">原始路径数据</param>
        /// <param name="sourceX">源X偏移</param>
        /// <param name="sourceY">源Y偏移</param>
        /// <param name="sourceHeight">源高度</param>
        /// <param name="scale">缩放比例</param>
        /// <param name="targetOffsetX">目标X偏移</param>
        /// <param name="targetOffsetY">目标Y偏移</param>
        /// <returns>缩放后的路径数据</returns>
        private string ScalePathCoordinates(string pathData, double sourceX, double sourceY, double sourceHeight, double scale, double targetOffsetX, double targetOffsetY)
        {
            try
            {
                // 匹配路径中的数字（包括小数和负数）
                var numberPattern = @"-?\d+(?:\.\d+)?";
                var result = System.Text.RegularExpressions.Regex.Replace(pathData, numberPattern, match =>
                {
                    if (double.TryParse(match.Value, out double value))
                    {
                        // 检查这个数字前面的字符，判断是X坐标还是Y坐标
                        var beforeMatch = pathData.Substring(0, match.Index);
                        var lastCommand = GetLastPathCommand(beforeMatch);
                        var isYCoordinate = IsYCoordinate(beforeMatch, lastCommand);
                        
                        double scaledValue;
                        if (isYCoordinate)
                        {
                            // Y坐标：优化基线对齐，确保字符从基线开始
                            // 使用与SvgProcessorService一致的转换逻辑
                            scaledValue = targetOffsetY + (value - sourceY) * scale;
                            
                            // 确保Y坐标在合理范围内（字体坐标系统：-150到850）
                            scaledValue = Math.Max(-150, Math.Min(850, scaledValue));
                        }
                        else
                        {
                            // X坐标
                            scaledValue = targetOffsetX + (value - sourceX) * scale;
                        }
                        
                        return scaledValue.ToString("F2");
                    }
                    return match.Value;
                });
                
                return result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"缩放坐标失败: {ex.Message}");
                return pathData;
            }
        }
        
        /// <summary>
        /// 获取路径中的最后一个命令
        /// </summary>
        private string GetLastPathCommand(string pathBefore)
        {
            var commandPattern = @"[MmLlHhVvCcSsQqTtAaZz]";
            var matches = System.Text.RegularExpressions.Regex.Matches(pathBefore, commandPattern);
            return matches.Count > 0 ? matches[matches.Count - 1].Value : "M";
        }
        
        /// <summary>
        /// 判断当前数字是否为Y坐标
        /// </summary>
        private bool IsYCoordinate(string pathBefore, string lastCommand)
        {
            // 简化的判断逻辑：计算最后一个命令后的数字个数
            var lastCommandIndex = pathBefore.LastIndexOf(lastCommand);
            if (lastCommandIndex >= 0)
            {
                var afterCommand = pathBefore.Substring(lastCommandIndex + 1);
                var numberCount = System.Text.RegularExpressions.Regex.Matches(afterCommand, @"-?\d+(?:\.\d+)?").Count;
                
                // 对于大多数命令，奇数位置是X坐标，偶数位置是Y坐标
                return numberCount % 2 == 1;
            }
            return false;
        }
        
        /// <summary>
        /// 获取源SVG的高度（用于Y坐标翻转）
        /// </summary>
        private double GetSourceHeight(string pathData)
        {
            // 简化实现：返回一个合理的默认值
            return 100;
        }
        
        /// <summary>
        /// 提取path元素
        /// </summary>
        private void ExtractPathElements(string svgContent, List<string> pathCommands)
        {
            var pathPattern = @"<path[^>]*d\s*=\s*[""']([^""']*)[""'][^>]*>";
            var matches = System.Text.RegularExpressions.Regex.Matches(svgContent, pathPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                if (match.Groups.Count > 1)
                {
                    var pathData = match.Groups[1].Value.Trim();
                    if (!string.IsNullOrEmpty(pathData))
                    {
                        pathCommands.Add(pathData);
                        Debug.WriteLine($"提取path元素: {pathData}");
                    }
                }
            }
        }
        
        /// <summary>
        /// 提取rect元素并转换为path
        /// </summary>
        private void ExtractRectElements(string svgContent, List<string> pathCommands)
        {
            var rectPattern = @"<rect[^>]*>";
            var matches = System.Text.RegularExpressions.Regex.Matches(svgContent, rectPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                var rectElement = match.Value;
                var x = ExtractAttribute(rectElement, "x", "0");
                var y = ExtractAttribute(rectElement, "y", "0");
                var width = ExtractAttribute(rectElement, "width", "0");
                var height = ExtractAttribute(rectElement, "height", "0");
                var fill = ExtractAttribute(rectElement, "fill", "black");
                var stroke = ExtractAttribute(rectElement, "stroke", "none");
                var strokeWidth = ExtractAttribute(rectElement, "stroke-width", "1");
                
                if (double.TryParse(x, out double xVal) && double.TryParse(y, out double yVal) &&
                    double.TryParse(width, out double wVal) && double.TryParse(height, out double hVal))
                {
                    string pathData;
                    
                    // 如果fill="none"且有stroke，生成边框路径
                    if (fill.ToLower() == "none" && stroke.ToLower() != "none" && double.TryParse(strokeWidth, out double swVal))
                    {
                        var halfStroke = swVal / 2;
                        // 生成边框路径（四条边）
                        pathData = $"M{xVal},{yVal + halfStroke} L{xVal + wVal},{yVal + halfStroke} L{xVal + wVal},{yVal - halfStroke} L{xVal},{yVal - halfStroke} z " +
                                  $"M{xVal + wVal - halfStroke},{yVal} L{xVal + wVal - halfStroke},{yVal + hVal} L{xVal + wVal + halfStroke},{yVal + hVal} L{xVal + wVal + halfStroke},{yVal} z " +
                                  $"M{xVal + wVal},{yVal + hVal - halfStroke} L{xVal},{yVal + hVal - halfStroke} L{xVal},{yVal + hVal + halfStroke} L{xVal + wVal},{yVal + hVal + halfStroke} z " +
                                  $"M{xVal + halfStroke},{yVal + hVal} L{xVal + halfStroke},{yVal} L{xVal - halfStroke},{yVal} L{xVal - halfStroke},{yVal + hVal} z";
                    }
                    else
                    {
                        // 生成填充矩形路径
                        pathData = $"M{xVal},{yVal} h{wVal} v{hVal} h-{wVal} z";
                    }
                    
                    pathCommands.Add(pathData);
                    Debug.WriteLine($"转换rect为path: {pathData}");
                }
            }
        }
        
        /// <summary>
        /// 提取line元素并转换为path
        /// </summary>
        private void ExtractLineElements(string svgContent, List<string> pathCommands)
        {
            // 首先查找所有的g元素及其transform属性
            var gPattern = @"<g[^>]*transform\s*=\s*[""']([^""']*)[""'][^>]*>([\s\S]*?)</g>";
            var gMatches = System.Text.RegularExpressions.Regex.Matches(svgContent, gPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            
            foreach (System.Text.RegularExpressions.Match gMatch in gMatches)
            {
                var transformAttr = gMatch.Groups[1].Value;
                var gContent = gMatch.Groups[2].Value;
                
                // 解析transform属性中的translate和scale值
                double translateX = 0, translateY = 0;
                double scaleX = 1, scaleY = 1;
                
                var translateMatch = System.Text.RegularExpressions.Regex.Match(transformAttr, @"translate\s*\(\s*([^,\s]+)\s*,?\s*([^\)\s]*)\s*\)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (translateMatch.Success)
                {
                    double.TryParse(translateMatch.Groups[1].Value, out translateX);
                    if (translateMatch.Groups[2].Success && !string.IsNullOrEmpty(translateMatch.Groups[2].Value))
                    {
                        double.TryParse(translateMatch.Groups[2].Value, out translateY);
                    }
                }
                
                var scaleMatch = System.Text.RegularExpressions.Regex.Match(transformAttr, @"scale\s*\(\s*([^,\s]+)\s*,?\s*([^\)\s]*)\s*\)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (scaleMatch.Success)
                {
                    double.TryParse(scaleMatch.Groups[1].Value, out scaleX);
                    if (scaleMatch.Groups[2].Success && !string.IsNullOrEmpty(scaleMatch.Groups[2].Value))
                    {
                        double.TryParse(scaleMatch.Groups[2].Value, out scaleY);
                    }
                    else
                    {
                        scaleY = scaleX; // 如果只有一个值，X和Y使用相同的缩放
                    }
                }
                
                Debug.WriteLine($"解析transform - translate: x={translateX}, y={translateY}, scale: x={scaleX}, y={scaleY}");
                
                // 在g元素内容中查找line元素
                var linePattern = @"<line[^>]*>";
                var lineMatches = System.Text.RegularExpressions.Regex.Matches(gContent, linePattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                
                foreach (System.Text.RegularExpressions.Match lineMatch in lineMatches)
                {
                    var lineElement = lineMatch.Value;
                    var x1 = ExtractAttribute(lineElement, "x1", "0");
                    var y1 = ExtractAttribute(lineElement, "y1", "0");
                    var x2 = ExtractAttribute(lineElement, "x2", "0");
                    var y2 = ExtractAttribute(lineElement, "y2", "0");
                    var strokeWidth = ExtractAttribute(lineElement, "stroke-width", "1");
                    
                    if (double.TryParse(x1, out double x1Val) && double.TryParse(y1, out double y1Val) &&
                        double.TryParse(x2, out double x2Val) && double.TryParse(y2, out double y2Val) &&
                        double.TryParse(strokeWidth, out double swVal))
                    {
                        // 应用transform变换（先缩放后平移）
                        x1Val = x1Val * scaleX + translateX;
                        y1Val = y1Val * scaleY + translateY;
                        x2Val = x2Val * scaleX + translateX;
                        y2Val = y2Val * scaleY + translateY;
                        
                        // 将线条转换为矩形路径以保持可见性
                        var halfWidth = swVal / 2;
                        var pathData = $"M{x1Val},{y1Val - halfWidth} L{x2Val},{y2Val - halfWidth} L{x2Val},{y2Val + halfWidth} L{x1Val},{y1Val + halfWidth} z";
                        pathCommands.Add(pathData);
                        Debug.WriteLine($"转换line为path (应用transform): {pathData}");
                    }
                }
            }
            
            // 处理不在g元素内的line元素
            var directLinePattern = @"<line[^>]*>";
            var directMatches = System.Text.RegularExpressions.Regex.Matches(svgContent, directLinePattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            
            foreach (System.Text.RegularExpressions.Match match in directMatches)
            {
                // 检查这个line是否已经在g元素内处理过了
                bool isInsideG = false;
                foreach (System.Text.RegularExpressions.Match gMatch in gMatches)
                {
                    if (gMatch.Groups[2].Value.Contains(match.Value))
                    {
                        isInsideG = true;
                        break;
                    }
                }
                
                if (!isInsideG)
                {
                    var lineElement = match.Value;
                    var x1 = ExtractAttribute(lineElement, "x1", "0");
                    var y1 = ExtractAttribute(lineElement, "y1", "0");
                    var x2 = ExtractAttribute(lineElement, "x2", "0");
                    var y2 = ExtractAttribute(lineElement, "y2", "0");
                    var strokeWidth = ExtractAttribute(lineElement, "stroke-width", "1");
                    
                    if (double.TryParse(x1, out double x1Val) && double.TryParse(y1, out double y1Val) &&
                        double.TryParse(x2, out double x2Val) && double.TryParse(y2, out double y2Val) &&
                        double.TryParse(strokeWidth, out double swVal))
                    {
                        // 将线条转换为矩形路径以保持可见性
                        var halfWidth = swVal / 2;
                        var pathData = $"M{x1Val},{y1Val - halfWidth} L{x2Val},{y2Val - halfWidth} L{x2Val},{y2Val + halfWidth} L{x1Val},{y1Val + halfWidth} z";
                        pathCommands.Add(pathData);
                        Debug.WriteLine($"转换line为path (直接): {pathData}");
                    }
                }
            }
        }
        
        /// <summary>
        /// 提取circle元素并转换为path
        /// </summary>
        private void ExtractCircleElements(string svgContent, List<string> pathCommands)
        {
            var circlePattern = @"<circle[^>]*>";
            var matches = System.Text.RegularExpressions.Regex.Matches(svgContent, circlePattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                var circleElement = match.Value;
                var cx = ExtractAttribute(circleElement, "cx", "0");
                var cy = ExtractAttribute(circleElement, "cy", "0");
                var r = ExtractAttribute(circleElement, "r", "0");
                
                if (double.TryParse(cx, out double cxVal) && double.TryParse(cy, out double cyVal) &&
                    double.TryParse(r, out double rVal))
                {
                    // 使用贝塞尔曲线近似圆形
                    var pathData = $"M{cxVal - rVal},{cyVal} A{rVal},{rVal} 0 1,1 {cxVal + rVal},{cyVal} A{rVal},{rVal} 0 1,1 {cxVal - rVal},{cyVal} z";
                    pathCommands.Add(pathData);
                    Debug.WriteLine($"转换circle为path: {pathData}");
                }
            }
        }
        
        /// <summary>
        /// 提取ellipse元素并转换为path
        /// </summary>
        private void ExtractEllipseElements(string svgContent, List<string> pathCommands)
        {
            var ellipsePattern = @"<ellipse[^>]*>";
            var matches = System.Text.RegularExpressions.Regex.Matches(svgContent, ellipsePattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                var ellipseElement = match.Value;
                var cx = ExtractAttribute(ellipseElement, "cx", "0");
                var cy = ExtractAttribute(ellipseElement, "cy", "0");
                var rx = ExtractAttribute(ellipseElement, "rx", "0");
                var ry = ExtractAttribute(ellipseElement, "ry", "0");
                
                if (double.TryParse(cx, out double cxVal) && double.TryParse(cy, out double cyVal) &&
                    double.TryParse(rx, out double rxVal) && double.TryParse(ry, out double ryVal))
                {
                    var pathData = $"M{cxVal - rxVal},{cyVal} A{rxVal},{ryVal} 0 1,1 {cxVal + rxVal},{cyVal} A{rxVal},{ryVal} 0 1,1 {cxVal - rxVal},{cyVal} z";
                    pathCommands.Add(pathData);
                    Debug.WriteLine($"转换ellipse为path: {pathData}");
                }
            }
        }
        
        /// <summary>
        /// 提取polygon元素并转换为path
        /// </summary>
        private void ExtractPolygonElements(string svgContent, List<string> pathCommands)
        {
            var polygonPattern = @"<polygon[^>]*points\s*=\s*[""']([^""']*)[""'][^>]*>";
            var matches = System.Text.RegularExpressions.Regex.Matches(svgContent, polygonPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                if (match.Groups.Count > 1)
                {
                    var points = match.Groups[1].Value.Trim();
                    var pathData = ConvertPointsToPath(points, true);
                    if (!string.IsNullOrEmpty(pathData))
                    {
                        pathCommands.Add(pathData);
                        Debug.WriteLine($"转换polygon为path: {pathData}");
                    }
                }
            }
        }
        
        /// <summary>
        /// 提取polyline元素并转换为path
        /// </summary>
        private void ExtractPolylineElements(string svgContent, List<string> pathCommands)
        {
            var polylinePattern = @"<polyline[^>]*points\s*=\s*[""']([^""']*)[""'][^>]*>";
            var matches = System.Text.RegularExpressions.Regex.Matches(svgContent, polylinePattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                if (match.Groups.Count > 1)
                {
                    var points = match.Groups[1].Value.Trim();
                    var pathData = ConvertPointsToPath(points, false);
                    if (!string.IsNullOrEmpty(pathData))
                    {
                        pathCommands.Add(pathData);
                        Debug.WriteLine($"转换polyline为path: {pathData}");
                    }
                }
            }
        }
        
        /// <summary>
        /// 从元素中提取属性值
        /// </summary>
        private string ExtractAttribute(string element, string attributeName, string defaultValue)
        {
            var pattern = $@"{attributeName}\s*=\s*[""']([^""']*)[""']";
            var match = System.Text.RegularExpressions.Regex.Match(element, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            return match.Success ? match.Groups[1].Value : defaultValue;
        }
        
        /// <summary>
        /// 将点坐标转换为路径数据
        /// </summary>
        private string ConvertPointsToPath(string points, bool closePath)
        {
            try
            {
                var coords = points.Split(new char[] { ' ', ',', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                if (coords.Length < 4) return null; // 至少需要两个点
                
                var pathData = new StringBuilder();
                
                for (int i = 0; i < coords.Length - 1; i += 2)
                {
                    if (double.TryParse(coords[i], out double x) && double.TryParse(coords[i + 1], out double y))
                    {
                        if (i == 0)
                            pathData.Append($"M{x},{y}");
                        else
                            pathData.Append($" L{x},{y}");
                    }
                }
                
                if (closePath)
                    pathData.Append(" z");
                    
                return pathData.ToString();
            }
            catch
            {
                return null;
            }
        }
        
        /// <summary>
        /// 转换SVG文件到字体
        /// </summary>
        /// <param name="svgFiles">SVG文件列表</param>
        /// <param name="outputFolder">输出文件夹</param>
        /// <param name="fileName">输出文件名（可能包含批次后缀）</param>
        /// <param name="config">Fontello CLI配置</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <param name="performanceSettings">性能设置</param>
        /// <param name="fontName">字体内部名称（不包含批次后缀）</param>
        /// <param name="fontFamily">字体族名称</param>
        /// <param name="fontAuthor">字体作者</param>
        /// <param name="fontVersion">字体版本</param>
        /// <returns>转换是否成功</returns>
        public async Task<bool> ConvertSvgToFontAsync(
            List<string> svgFiles, 
            string outputFolder, 
            string fileName, 
            FontelloCliConfig config,
            CancellationToken cancellationToken = default,
            PerformanceSettings performanceSettings = null,
            string fontName = null, string fontFamily = null, string fontAuthor = null, string fontVersion = null)
        {
            try
            {
                if (!ValidateFontelloCliConfig(config))
                {
                    Debug.WriteLine("Fontello CLI配置无效");
                    return false;
                }
                
                // 确保输出目录存在
                Directory.CreateDirectory(outputFolder);
                
                // 创建临时工作目录（在程序目录下，便于调试）
                var tempDir = Path.Combine(outputFolder, $"fontello_temp_{Guid.NewGuid():N}");
                Directory.CreateDirectory(tempDir);
                
                try
                {
                    // 生成Fontello配置文件
                    var configPath = GenerateFontelloConfig(svgFiles, fontName, tempDir, cancellationToken, fontFamily, fontAuthor, fontVersion);
                    if (string.IsNullOrEmpty(configPath))
                    {
                        Debug.WriteLine("生成Fontello配置文件失败");
                        return false;
                    }
                    
                    // 执行Fontello CLI命令
                    Debug.WriteLine($"开始执行Fontello CLI命令，配置文件: {configPath}");
                    Debug.WriteLine($"输出文件夹: {outputFolder}");
                    var success = await ExecuteFontelloCliAsync(config, configPath, outputFolder, tempDir, cancellationToken, performanceSettings);
                    Debug.WriteLine($"Fontello CLI执行结果: {success}");
                    
                    return success;
                }
                finally
                {
                    // 保留临时目录用于调试
                    Debug.WriteLine($"临时目录保留在: {tempDir}");
                    Debug.WriteLine("请手动检查临时文件以进行调试");
                    
                    // 暂时注释掉清理代码用于调试
                    /*
                    try
                    {
                        if (Directory.Exists(tempDir))
                        {
                            Directory.Delete(tempDir, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"清理临时目录失败: {ex.Message}");
                    }
                    */
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Fontello CLI转换过程中发生错误: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 生成Fontello配置文件
        /// </summary>
        /// <param name="svgFiles">SVG文件列表</param>
        /// <param name="fontName">字体名称</param>
        /// <param name="tempDir">临时目录</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <param name="fontFamily">字体族名称</param>
        /// <param name="fontAuthor">字体作者</param>
        /// <param name="fontVersion">字体版本</param>
        /// <returns>配置文件路径</returns>
        private string GenerateFontelloConfig(
            List<string> svgFiles, 
            string fontName, 
            string tempDir, 
            CancellationToken cancellationToken,
            string fontFamily = null,
            string fontAuthor = null,
            string fontVersion = null)
        {
            try
            {
                var glyphs = new List<object>();
                int currentUnicode = 0xE000; // 从私有使用区域开始
                
                foreach (var svgFile in svgFiles)
                {
                    if (cancellationToken.IsCancellationRequested)
                        return null;
                    
                    var fileName = Path.GetFileNameWithoutExtension(svgFile);
                    int unicode;
                    
                    // 尝试解析Unicode编码
                    if (int.TryParse(fileName, System.Globalization.NumberStyles.HexNumber, null, out unicode))
                    {
                        Debug.WriteLine($"使用文件名作为Unicode编码: {fileName} -> U+{unicode:X4}");
                    }
                    else
                    {
                        // 如果文件名不是十六进制，尝试从文件名中的字符获取Unicode编码
                        if (fileName.Length == 1)
                        {
                            // 单个字符文件名，直接获取其Unicode编码
                            unicode = (int)fileName[0];
                            Debug.WriteLine($"从单字符文件名获取Unicode编码: {fileName} -> U+{unicode:X4}");
                        }
                        else if (fileName.Length > 0)
                        {
                            // 多字符文件名，尝试获取第一个字符的Unicode编码
                            unicode = (int)fileName[0];
                            Debug.WriteLine($"从多字符文件名首字符获取Unicode编码: {fileName} -> U+{unicode:X4} (字符: {fileName[0]})");
                        }
                        else
                        {
                            // 空文件名或其他情况，分配私有使用区域编码
                            unicode = currentUnicode++;
                            Debug.WriteLine($"为文件 {fileName} 分配私有区域Unicode编码: U+{unicode:X4}");
                        }
                    }
                    
                    try
                    {
                        // 读取SVG内容
                        var svgContent = File.ReadAllText(svgFile);
                        
                        // 复制SVG文件到临时目录
                        var tempSvgPath = Path.Combine(tempDir, Path.GetFileName(svgFile));
                        File.WriteAllText(tempSvgPath, svgContent);
                        
                        // 提取SVG路径
                        Debug.WriteLine($"\n=== 处理文件: {fileName} ===");
                        Debug.WriteLine($"SVG内容长度: {svgContent.Length}");
                        Debug.WriteLine($"SVG内容前200字符: {svgContent.Substring(0, Math.Min(200, svgContent.Length))}");
                        
                        var svgPath = ExtractSvgPath(svgContent);
                        Debug.WriteLine($"提取的SVG路径: {svgPath}");
                        
                        if (string.IsNullOrEmpty(svgPath))
                        {
                            Debug.WriteLine($"警告: 文件 {fileName} 无法提取有效的SVG路径");
                            continue;
                        }
                        
                        // 计算实际字符宽度
                        double actualCharWidth;
                        var scaledPath = ScalePathToFontCoordinates(svgContent, svgPath, out actualCharWidth);
                        Debug.WriteLine($"实际字符宽度: {actualCharWidth:F2}");
                        
                        var glyph = new
                        {
                            uid = Guid.NewGuid().ToString("N").Substring(0, 8),
                            css = $"icon-{fileName.ToLower().Replace(" ", "-")}",
                            code = unicode,
                            src = "custom_icons",
                            selected = true,
                            svg = new
                            {
                                path = scaledPath,
                                width = (int)Math.Round(actualCharWidth)
                            }
                        };
                        
                        glyphs.Add(glyph);
                        Debug.WriteLine($"成功处理文件: {fileName}, Unicode: U+{unicode:X4}");
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"处理文件 {fileName} 时发生错误: {ex.Message}");
                    }
                }
                
                if (glyphs.Count == 0)
                {
                    Debug.WriteLine("没有有效的SVG文件可转换");
                    return null;
                }
                
                // 设置字体属性
                var actualFontName = fontName ?? "CustomFont";
                var actualFontFamily = fontFamily ?? "CustomFont";
                var actualFontAuthor = fontAuthor ?? "Unknown";
                var actualFontVersion = fontVersion ?? "1.0";
                
                // 创建Fontello配置对象
                var fontelloConfig = new
                {
                    name = actualFontName,
                    css_prefix_text = "icon-",
                    css_use_suffix = false,
                    hinting = true,
                    units_per_em = 1000,  // 与SvgProcessorService的FontEmSize保持一致
                    ascent = 800,         // 与SvgProcessorService的FontAscent保持一致
                    glyphs = glyphs
                };
                
                // 序列化为JSON
                var options = new JsonSerializerOptions
                {
                    WriteIndented = true
                };
                var json = JsonSerializer.Serialize(fontelloConfig, options);
                
                // 保存配置文件
                var configPath = Path.Combine(tempDir, "config.json");
                File.WriteAllText(configPath, json);
                
                Debug.WriteLine($"生成Fontello配置文件: {configPath}");
                Debug.WriteLine($"包含 {glyphs.Count} 个字符");
                Debug.WriteLine("=== 生成的config.json内容 ===");
                Debug.WriteLine(json);
                Debug.WriteLine("=== config.json内容结束 ===");
                
                return configPath;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"生成Fontello配置文件失败: {ex.Message}");
                return null;
            }
        }
        
        /// <summary>
        /// 从SVG内容中提取路径数据
        /// </summary>
        /// <param name="svgContent">SVG内容</param>
        /// <returns>路径数据</returns>
        private string ExtractSvgPath(string svgContent)
        {
            try
            {
                // 创建临时SVG文件用于专业库处理
                var tempSvgFile = Path.GetTempFileName();
                tempSvgFile = Path.ChangeExtension(tempSvgFile, ".svg");
                
                try
                {
                    File.WriteAllText(tempSvgFile, svgContent);
                    
                    // 使用专业SVG处理服务
                    var processedPath = _svgProcessor.ProcessSvgFile(tempSvgFile);
                    Debug.WriteLine($"专业SVG处理结果: {processedPath}");
                    
                    return processedPath;
                }
                finally
                {
                    // 清理临时文件
                    if (File.Exists(tempSvgFile))
                    {
                        File.Delete(tempSvgFile);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"专业SVG处理失败，回退到默认处理: {ex.Message}");
                
                // 回退到原有的正则表达式处理方式
                return ExtractSvgPathFallback(svgContent);
            }
        }
        
        /// <summary>
        /// 回退的SVG路径提取方法（使用正则表达式）
        /// </summary>
        /// <param name="svgContent">SVG内容</param>
        /// <returns>路径数据</returns>
        private string ExtractSvgPathFallback(string svgContent)
        {
            try
            {
                var pathCommands = new List<string>();
                
                // 提取所有path元素
                ExtractPathElements(svgContent, pathCommands);
                
                // 提取rect元素并转换为path
                ExtractRectElements(svgContent, pathCommands);
                
                // 提取line元素并转换为path
                ExtractLineElements(svgContent, pathCommands);
                
                // 提取circle元素并转换为path
                ExtractCircleElements(svgContent, pathCommands);
                
                // 提取ellipse元素并转换为path
                ExtractEllipseElements(svgContent, pathCommands);
                
                // 提取polygon元素并转换为path
                ExtractPolygonElements(svgContent, pathCommands);
                
                // 提取polyline元素并转换为path
                ExtractPolylineElements(svgContent, pathCommands);
                
                if (pathCommands.Count > 0)
                {
                    var combinedPath = string.Join(" ", pathCommands);
                    Debug.WriteLine($"原始SVG路径: {combinedPath}");
                    
                    // 解析viewBox并缩放路径坐标
                    double actualWidth;
                    var scaledPath = ScalePathToFontCoordinates(svgContent, combinedPath, out actualWidth);
                    Debug.WriteLine($"缩放后SVG路径: {scaledPath}");
                    return scaledPath;
                }
                
                // 如果没有找到任何图形元素，返回一个默认的矩形
                Debug.WriteLine("未找到任何SVG图形元素，使用默认矩形");
                return "M100 100h800v800h-800z";
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"回退SVG路径提取失败: {ex.Message}");
                return "M100 100h800v800h-800z";
            }
        }
        
        /// <summary>
        /// 执行Fontello CLI命令
        /// </summary>
        /// <param name="config">Fontello CLI配置</param>
        /// <param name="configPath">配置文件路径</param>
        /// <param name="outputFolder">输出文件夹</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <param name="performanceSettings">性能设置</param>
        /// <returns>是否成功</returns>
        private async Task<bool> ExecuteFontelloCliAsync(
            FontelloCliConfig config, 
            string configPath, 
            string outputFolder,
            string tempDir,
            CancellationToken cancellationToken,
            PerformanceSettings performanceSettings = null)
        {
            var nodePath = Path.Combine(config.NodeJsPath, "node.exe");
            
            // 构建 fontello-cli 命令参数
            // 正确的用法是: node bin/fontello-cli install --config ./path/to/config.json
            string arguments;
            
            // 如果指定了FontelloCliPath，则使用本地路径
            if (!string.IsNullOrWhiteSpace(config.FontelloCliPath))
            {
                var fontelloCliScript = Path.Combine(config.FontelloCliPath, "bin", "fontello-cli");
                if (File.Exists(fontelloCliScript))
                {
                    arguments = $"\"{fontelloCliScript}\" install --config \"{configPath}\"";
                }
                else
                {
                    // 如果找不到本地脚本，使用全局安装的fontello-cli
                    arguments = $"fontello-cli install --config \"{configPath}\"";
                }
            }
            else
            {
                // 使用全局安装的fontello-cli
                arguments = $"fontello-cli install --config \"{configPath}\"";
            }
            
            Debug.WriteLine($"Node.js路径: {nodePath}");
            Debug.WriteLine($"执行参数: {arguments}");
            Debug.WriteLine($"工作目录: {outputFolder}");
            
            var processStartInfo = new ProcessStartInfo
            {
                FileName = nodePath,
                Arguments = arguments,
                WorkingDirectory = outputFolder,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding = Encoding.UTF8
            };
            
            using (var process = new Process { StartInfo = processStartInfo })
            {
                var outputBuilder = new StringBuilder();
                var errorBuilder = new StringBuilder();
                
                process.OutputDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        outputBuilder.AppendLine(e.Data);
                        Debug.WriteLine($"Fontello CLI: {e.Data}");
                    }
                };
                
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        errorBuilder.AppendLine(e.Data);
                        Debug.WriteLine($"Fontello CLI Error: {e.Data}");
                    }
                };
                
                try
                {
                    Debug.WriteLine($"执行Fontello CLI命令: {processStartInfo.Arguments}");
                    
                    process.Start();
                    
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    
                    var timeoutSeconds = performanceSettings?.ProcessTimeoutSeconds ?? 300; // 默认5分钟
                    var timeoutMs = timeoutSeconds * 1000;
                    var startTime = DateTime.Now;
                    
                    while (!process.HasExited && !cancellationToken.IsCancellationRequested)
                    {
                        if ((DateTime.Now - startTime).TotalMilliseconds > timeoutMs)
                        {
                            Debug.WriteLine($"Fontello CLI进程执行超时（{timeoutSeconds}秒），强制终止");
                            break;
                        }
                        
                        await Task.Delay(100, cancellationToken);
                    }
                    
                    if (cancellationToken.IsCancellationRequested || !process.HasExited)
                    {
                        if (!process.HasExited)
                        {
                            try
                            {
                                process.Kill();
                                await Task.Delay(1000);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine($"终止进程时出错: {ex.Message}");
                            }
                        }
                        
                        return false;
                    }
                    
                    if (!process.HasExited)
                    {
                        process.WaitForExit(5000);
                    }
                    
                    var success = process.ExitCode == 0;
                    
                    if (success)
                    {
                        Debug.WriteLine("Fontello CLI转换成功");
                        
                        // Fontello CLI 会下载并解压 zip 文件到工作目录
                        // 字体文件应该已经在输出文件夹中
                        var workingDir = outputFolder;
                        
                        // 查找fontello生成的字体文件（在fontello-xxx/font/目录中）
                        var fontFiles = new List<string>();
                        if (Directory.Exists(workingDir))
                        {
                            // 查找fontello-xxx目录
                            var fontelloDirs = Directory.GetDirectories(workingDir, "fontello-*");
                            foreach (var fontelloDir in fontelloDirs)
                            {
                                var fontDir = Path.Combine(fontelloDir, "font");
                                if (Directory.Exists(fontDir))
                                {
                                    fontFiles.AddRange(Directory.GetFiles(fontDir, "*.ttf"));
                                    fontFiles.AddRange(Directory.GetFiles(fontDir, "*.woff"));
                                    fontFiles.AddRange(Directory.GetFiles(fontDir, "*.woff2"));
                                }
                            }
                        }
                        
                        if (fontFiles.Count > 0)
                        {
                            Debug.WriteLine($"在fontello目录中找到 {fontFiles.Count} 个字体文件");
                            
                            // 复制字体文件到输出文件夹根目录
                            foreach (var fontFile in fontFiles)
                            {
                                var fileName = Path.GetFileName(fontFile);
                                var destPath = Path.Combine(outputFolder, fileName);
                                File.Copy(fontFile, destPath, true);
                                Debug.WriteLine($"复制字体文件: {fileName} -> {destPath}");
                            }
                            
                            return true;
                        }
                        else
                        {
                            Debug.WriteLine("未找到生成的字体文件");
                            Debug.WriteLine($"工作目录: {workingDir}");
                            
                            // 列出工作目录中的所有文件以便调试
                            if (Directory.Exists(workingDir))
                            {
                                var allFiles = Directory.GetFiles(workingDir, "*", SearchOption.AllDirectories);
                                Debug.WriteLine($"工作目录中的所有文件: {string.Join(", ", allFiles.Select(Path.GetFileName))}");
                            }
                            
                            return false;
                        }
                    }
                    else
                    {
                        var errorOutput = errorBuilder.ToString();
                        Debug.WriteLine($"Fontello CLI转换失败，退出代码: {process.ExitCode}");
                        if (!string.IsNullOrEmpty(errorOutput))
                        {
                            Debug.WriteLine($"错误信息: {errorOutput}");
                        }
                        return false;
                    }
                }
                catch (OperationCanceledException)
                {
                    if (!process.HasExited)
                    {
                        try
                        {
                            process.Kill();
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine($"取消时终止进程出错: {ex.Message}");
                        }
                    }
                    return false;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"执行Fontello CLI时出错: {ex.Message}");
                    if (!process.HasExited)
                    {
                        try
                        {
                            process.Kill();
                        }
                        catch
                        {
                            // 忽略终止进程时的错误
                        }
                    }
                    return false;
                }
            }
        }
    }
}